package com.yc.controller;

import com.yc.domain.UserBean;
import com.yc.model.ResponseResult;
import com.yc.model.UserVO;
import com.yc.service.UserBiz;
import com.yc.uitls.JwtTokenUtil;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zwei
 * @create 2024-09-26 15:14
 */
@RestController
@RequestMapping("/ordersecurity")
@Slf4j
public class UserConteoller {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserBiz userBiz;
    //登录
    @PostMapping(value = "login")
    public ResponseResult login(@RequestBody UserVO userVO, HttpSession session){
        Authentication authentication=authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(userVO.getUsername(),userVO.getPwd())
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails= (UserDetails) authentication.getPrincipal();
        //生成JWT负载
        Map<String,String> playload=new HashMap<>();
        playload.put("username",userDetails.getUsername());
        playload.put("userid",String.valueOf(((UserBean)userDetails).getId()));
        playload.put("role","user");
        playload.put("email",((UserBean)userDetails).getEmail());
        //生成token
        String token=jwtTokenUtil.encodeJWT(playload);
        return ResponseResult.ok("登录成功").setData(token);
    }
    //注册
    @PostMapping("/register")
    public ResponseResult register(@RequestBody @Valid UserVO userVO) {
        try {
            int userid=userBiz.regUser(userVO);
            userVO.setUserid(userid);           //新用户id
            userVO.setPwd("");          //密码置空
            return ResponseResult.ok("注册成功").setData(userVO);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("注册失败");
        }
    }
    //退出
    @PostMapping("/logout")
    public ResponseResult logout(){
        return ResponseResult.ok("退出成功");
    }
    //鉴权测试
    @GetMapping("/test")
    public ResponseResult test(){
        log.info("权限验证成功");
        //用security框架对当前用户进行鉴权
        UserBean userBean= (UserBean) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("当前用户为："+userBean.getUsername());
        userBean.setPassword("");
        return ResponseResult.ok().setData(userBean);
    }
}
